#include "Vacation.h"
#include "ui_Vacation.h"
#include "Server.h"
#include <QMessageBox>
#include <QSqlQuery>
#include <QSqlError>
#include <QBitmap>
#include <QStyleOption>
#include <QMouseEvent>
#include <QPainter>
#include "mymessagebox.h"

Vacation::Vacation(Server *server, QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Vacation)
    , serverWindow(server)
{
    ui->setupUi(this);

    // 隐藏原生标题栏
    setWindowFlags(Qt::FramelessWindowHint | Qt::Dialog);

    // 防止窗口背景透明
    setAttribute(Qt::WA_TranslucentBackground, false);

    model = new QStandardItemModel(this); // 初始化模型
    ui->list->setModel(model); // 设置模型到 QListView
    updateLeaveList();  // 初始化时加载请假申请列表
    connect(ui->list->selectionModel(), &QItemSelectionModel::currentChanged, this, &Vacation::on_list_clicked);
}

Vacation::~Vacation()
{
    delete ui;
}

// 实现窗口拖动功能
void Vacation::mousePressEvent(QMouseEvent *event)
{
    // 检查是否点击了自定义标题栏
    if (event->button() == Qt::LeftButton && event->pos().y() <= 60) {
        m_isTitleBarClicked = true;
        m_dragPosition = event->globalPos() - frameGeometry().topLeft();
        event->accept();
    } else {
        m_isTitleBarClicked = false;
        // 让事件继续传播，确保其他控件能响应点击事件
        QWidget::mousePressEvent(event);
    }
}

void Vacation::mouseMoveEvent(QMouseEvent *event)
{
    // 只有在点击了标题栏之后才允许拖动
    if (m_isTitleBarClicked && (event->buttons() & Qt::LeftButton)) {
        move(event->globalPos() - m_dragPosition);
        event->accept();
    } else {
        // 让事件继续传播，确保其他控件能响应移动事件
        QWidget::mouseMoveEvent(event);
    }
}

void Vacation::paintEvent(QPaintEvent *event)
{
    // 1. 绘制样式（QSS）
    QStyleOption opt;
    opt.initFrom(this);
    QPainter p(this);
    style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this); // 绘制样式

    // 2. 设置掩码，约定 painter 绘制区域
    QBitmap bmp(this->size());
    bmp.fill(Qt::white); // 填充 bitmap

    QPainter painter(&bmp);
    painter.setPen(Qt::NoPen);
    painter.setBrush(Qt::black); // 掩码值
    painter.drawRoundedRect(bmp.rect(), 30, 30); // 在 bitmap 中绘制圆角矩形

    // 设置掩码以确定本控件可绘制区域
    setMask(bmp);

    // 调用基类的 paintEvent
    QWidget::paintEvent(event);
}

void Vacation::on_returnButton_clicked()
{
    this->close();
    serverWindow->show();
}


void Vacation::updateLeaveList()
{
    model->clear(); // 清空模型

    QSqlQuery query;
    query.prepare("SELECT 工号, 姓名, 申请时间 FROM LeaveTable WHERE 申请状态 = 0");
    if (query.exec()) {
        while (query.next()) {
            QString employeeId = query.value(0).toString();
            QString employeeName = query.value(1).toString();
            QString applyTime = query.value(2).toString();

            // 创建新项并添加到模型
            QString listItem = QString("%1 - %2 - %3").arg(employeeId).arg(employeeName).arg(applyTime);
            model->appendRow(new QStandardItem(listItem));
        }
    } else {
        qDebug() << "Failed to query LeaveTable:" << query.lastError();
    }
}

void Vacation::on_list_clicked(const QModelIndex &index)
{
    if (!index.isValid()) return; // 确保选择有效

    QStringList data = model->item(index.row())->text().split(" - ");
    selectedEmployeeId = data.at(0);
    selectedEmployeeName = data.at(1);
    selectedApplyTime = data.at(2);

    // 查询请假详情
    QSqlQuery query;
    query.prepare("SELECT 开始日期, 结束日期, 请假原因, 考勤组号 FROM LeaveTable WHERE 工号 = :employeeId AND 姓名 = :employeeName AND 申请时间 = :applyTime");
    query.bindValue(":employeeId", selectedEmployeeId);
    query.bindValue(":employeeName", selectedEmployeeName);
    query.bindValue(":applyTime", selectedApplyTime);

    if (query.exec() && query.next()) {
        ui->num->setText(query.value(3).toString());  // 考勤组号
        ui->start->setText(query.value(0).toString()); // 开始日期
        ui->end->setText(query.value(1).toString());   // 结束日期
        ui->reason->setPlainText(query.value(2).toString()); // 请假原因
    } else {
        qDebug() << "Failed to query LeaveTable details:" << query.lastError();
    }
}

void Vacation::clearDetails()
{
    ui->num->clear();
    ui->start->clear();
    ui->end->clear();
    ui->reason->clear();
    selectedEmployeeId.clear();
    selectedEmployeeName.clear();
}

void Vacation::on_yes_clicked()
{
    if (selectedEmployeeId.isEmpty()) {
        // QMessageBox::warning(this, "警告", "请选择申请记录");
        MyMessageBox msgBox;
        msgBox.setWindowTitle("警告");
        msgBox.setText("请选择申请记录");
        msgBox.setButton("确定");
        msgBox.exec();
        return;
    }

    QSqlQuery query;

    // 修改申请状态为 1（通过）
    query.prepare("UPDATE LeaveTable SET 申请状态 = 1 WHERE 工号 = :employeeId AND 姓名 = :employeeName AND 申请时间 = :applyTime");
    query.bindValue(":employeeId", selectedEmployeeId);
    query.bindValue(":employeeName", selectedEmployeeName);
    query.bindValue(":applyTime", selectedApplyTime);

    if (!query.exec()) {
        qDebug() << "Failed to update LeaveTable:" << query.lastError();
        return;
    }

    // QMessageBox::information(this, "成功", "审核通过");
    MyMessageBox msgBox;
    msgBox.setWindowTitle("成功");
    msgBox.setText("审核通过");
    msgBox.setButton("确定");
    msgBox.exec();

    clearDetails();
    updateLeaveList();  // 更新列表
}

void Vacation::on_no_clicked()
{
    if (selectedEmployeeId.isEmpty()) {
        // QMessageBox::warning(this, "警告", "请选择申请记录");
        MyMessageBox msgBox;
        msgBox.setWindowTitle("警告");
        msgBox.setText("请选择申请记录");
        msgBox.setButton("确定");
        msgBox.exec();
        return;
    }

    QSqlQuery query;

    // 修改申请状态为 2（未通过）
    query.prepare("UPDATE LeaveTable SET 申请状态 = 2 WHERE 工号 = :employeeId AND 姓名 = :employeeName AND 申请时间 = :applyTime");
    query.bindValue(":employeeId", selectedEmployeeId);
    query.bindValue(":employeeName", selectedEmployeeName);
    query.bindValue(":applyTime", selectedApplyTime);

    if (!query.exec()) {
        qDebug() << "Failed to update LeaveTable:" << query.lastError();
        return;
    }

    // QMessageBox::information(this, "成功", "审核未通过");
    MyMessageBox msgBox;
    msgBox.setWindowTitle("成功");
    msgBox.setText("审核未通过");
    msgBox.setButton("确定");
    msgBox.exec();

    clearDetails();
    updateLeaveList();  // 更新列表
}

